import { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Popconfirm,
  Divider,
  Tag,
  Space,
  Button,
  Input,
  Table,
  Drawer,
  Checkbox,
  Image,
} from 'antd';
import { PlusOutlined, SyncOutlined } from '@ant-design/icons';
import { connect,useIntl } from 'umi';
import moment from 'moment';
import MemberEdit from './components/memberEdit';
import UploadUtil from '@/components/UploadUtil';
import request from '@/utils/request';

const { Search } = Input;
const apiURL = '/api/services/app/Members/';
const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [record, setRecord] = useState({});
  const [payload, setPayload] = useState({ SkipCount: 0, MaxResultCount: 10, keywords: '' });
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, [pageIndex, pageSize]);

  const fetchDatas = () => {
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'GET',
      params: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize },
    }).then((resp)=>{
        var dataSource = resp.result?.items;
          setLoading(false);
          setDataSource(dataSource);
          setTotalCount(resp.result?.totalCount);
    });
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const handleDelete = (id: any) => {
    request(apiURL + 'Delete', {
      method: 'DELETE',
      params: { id },
    }).then(()=>{
      fetchDatas();
    });
  };

  const switchModal = (visible: boolean, record: any = null) => {
    setVisible(visible);
    setRecord(record);
  };

  const onSearch = (value: string) => {
    payload.keywords = value;
    setPayload(payload);
    fetchDatas();
  };

  const columns = [
    {
      title: intl.formatMessage({id:'pages.name'}),
      dataIndex: 'name',
    },
    {
      title: intl.formatMessage({id:'pages.userName'}),
      dataIndex: 'userName',
    },
    {
      title: intl.formatMessage({id:'pages.QRCode'}),
      render: (record: any) => (
        <>
          <Image
            width={30}
            src={UploadUtil.QRCodeServer + '?txt=' + record.cardNo + '&pixel=10'}
          />
        </>
      ),
    },
    {
      title: intl.formatMessage({id:'pages.memberType'}),
      dataIndex: 'memberType',
    },
    {
      title: intl.formatMessage({id:'pages.sex'}),
      dataIndex: 'sex',
      render: (text: any) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: intl.formatMessage({id:'pages.inActive'}),
      dataIndex: 'inActive',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: intl.formatMessage({id:'pages.creationTime'}),
      dataIndex: 'creationTime',
      render: (text: any) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
    },
    {
      title: intl.formatMessage({id:'pages.operation'}),
      render: (record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Popconfirm title={intl.formatMessage({id:'pages.delete?'})} onConfirm={() => handleDelete(record.id)}>
              <a>{intl.formatMessage({id:'pages.delete'})}</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a onClick={() => switchModal(true, record)}>{intl.formatMessage({id:'pages.edit'})}</a>
          </span>
        ) : null,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Space>
          <Button
            type="primary"
            onClick={fetchDatas}
            loading={loading}
            icon={<SyncOutlined />}
          >
            {intl.formatMessage({id:'pages.refresh'})}
          </Button>
          <Button type="primary" onClick={() => switchModal(true)} icon={<PlusOutlined />}>
            {intl.formatMessage({id:'pages.add'})}
          </Button>
          <Search
            style={{ width: 240 }}
            placeholder={intl.formatMessage({id:'pages.enterKeywords'})}
            onSearch={(value) => onSearch(value)}
          />
          <span>{hasSelected ? `${intl.formatMessage({id:'pages.select'})} ${selectedRowKeys.length} ${intl.formatMessage({id:'pages.PCS'})}` : ''}</span>
        </Space>
      </Card>
      <Table
        rowKey="id"
        loading={loading}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
        pagination={{
          onChange: (page: number) => {
            setPageIndex(page);
          },
          pageSize,
          total: totalCount,
        }}
      />
      <Drawer
        title={intl.formatMessage({id:'pages.member.edit'})}
        placement="right"
        visible={visible}
        destroyOnClose={true}
        onClose={() => switchModal(false)}
        width={600}
      >
        <MemberEdit
          record={record}
          fetchDatas={fetchDatas}
          closeDraw={() => switchModal(false)}
        />
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default connect(({ user }: API.IConnectState) => ({
  currentUser: user.currentUser,
}))(ViewPage);
